<?php
namespace my;
class JoDES {

	private static $_instance = NULL;

	private function __construct()
	{

	}
	/**
	 * @return JoDES
	 */
	public static function share() {
		if (is_null(self::$_instance)) {
			self::$_instance = new JoDES();
		}
		return self::$_instance;
	}

	/**
	 * 加密
	 * @param string $str 要处理的字符串
	 * @param string $key 加密Key，为8个字节长度
	 * @return string
	 */
	public function encode($str, $key) {
	//	$str = urlencode($str);
		$size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
		$str = self::pkcs5Pad($str, $size);
		$aaa = mcrypt_cbc(MCRYPT_DES, $key, $str, MCRYPT_ENCRYPT, $key);
    
      //  $aaa = mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_CBC, $key);
		$ret = base64_encode($aaa);
		return $ret;
	}

	/**
	 * 解析日志用的，不要删除
	 * @param string 
	 * @param int 
	 * @return string 成功时返回
	 */
	public static function des_decode_log($str){
		//$str = urldecode($str);
	    $des = Self::share();
	    $de = $des->decode($str, "xmcx0551");
	    $de = urldecode($de);
	    return $de;
    }
	/**
	 * 解密
	 * @param string $str 要处理的字符串
	 * @param string $key 解密Key，为8个字节长度
	 * @return string
	 */
	public function decode($str, $key) {
	//	$str = urldecode($str);
		$strBin = base64_decode($str);
		$str = mcrypt_cbc(MCRYPT_DES, $key, $strBin, MCRYPT_DECRYPT, $key);
		//
		//$str = mcrypt_encrypt(MCRYPT_DES, $key, $strBin, MCRYPT_MODE_CBC, $key);
		$str = self::pkcs5Unpad($str);
		return $str;
	}

	function hex2bin($hexData) {
		$binData = "";
		for ($i = 0; $i < strlen($hexData); $i += 2) {
			$binData .= chr(hexdec(substr($hexData, $i, 2)));
		}
		return $binData;
	}

	function pkcs5Pad($text, $blocksize) {
		$pad = $blocksize - (strlen($text) % $blocksize);
		return $text . str_repeat(chr($pad), $pad);
	}

	function pkcs5Unpad($text) {
		$pad = ord($text {strlen($text) - 1});
		if ($pad > strlen($text))
			return false;

		if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)
			return false;

		return substr($text, 0, - 1 * $pad);
	}

}